package cn.xspace.app.filemg.fragment;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.xspace.android.xafcommon.db.dbsub.BaseDbMg;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.LogUtil;

import java.io.File;
import java.util.ArrayList;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.util.CallBack;
import cn.xspace.app.filemg.util.FileMg;
import cn.xspace.app.filemg.view.MusicOrDocAdapter;


public class FileDocFragment extends Fragment {
    private Context mContext;
    private ArrayList<FileInfo> docList = new ArrayList<FileInfo>();
    private MusicOrDocAdapter mAdapter;
    private ListView mListView;
    private boolean checkFlag;
    private static CallBack mCallBack;
    private boolean isOver = false;
    private ChooseFileInfo chooseInfo = new ChooseFileInfo();

    public static FileDocFragment newInstance(CallBack callBack) {
        FileDocFragment newFragment = new FileDocFragment();
        mCallBack = callBack;
        return newFragment;

    }

    public void updateFile(FileInfo info) {
        try {
            if (info == null || info.getPath() == null) {
                return;
            }
            for (FileInfo infos : docList) {
                if (info.getPath().equals(infos.getPath())) {
                    return;
                }
            }
            docList.add(info);
            handler.sendEmptyMessage(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryOver() {
        isOver = true;
        handler.sendEmptyMessage(1);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (mAdapter != null) {
                        try {
                            mAdapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 1:

                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = FileDocFragment.this.getActivity();
        docList = BaseDbMg.getInstance().getFileMgDb().querySend("doc");
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        new MyAsyncTask().execute();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        handler.removeMessages(0);
        handler.removeMessages(1);
        super.onDestroy();
    }

    private void initData() {
        for (FileInfo info : docList) {
            for (FileInfo cInfo : chooseInfo.getFileList()) {
                if (cInfo.getPath().equals(info.getPath())) {
                    info.setCheckFlag(true);
                }
            }
        }
    }

    public void initChooseData(ChooseFileInfo chooseInfo) {
        this.chooseInfo = chooseInfo;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(BaseRProxy.file_music_doc, container, false);
        mListView = (ListView) view.findViewById(BaseRProxy.listview);
        mAdapter = new MusicOrDocAdapter(mContext, docList);
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                FileInfo info = docList.get(arg2);
                info.setCheckFlag(!info.isCheckFlag());
                mAdapter.notifyDataSetChanged();
                mCallBack.checkedInfo(info);
            }
        });
        mListView.setAdapter(mAdapter);
        return view;

    }

    private void getMyLocalFile(File f) {
        if (f == null || !f.exists())
            return;
        if (f.isDirectory()) {
            File[] files1 = f.listFiles();
            for (int j = 0; j < files1.length; j++) {
                File cfile = files1[j];
                getMyLocalFile(cfile);
            }
        } else {
            String fileName = f.getName();
            if (fileName.endsWith(".doc") || fileName.endsWith(".docx")
                    || fileName.endsWith(".xls") || fileName.endsWith(".ppt")) {
                addDocInfo(f);
            }
        }

    }

    private void addDocInfo(File file) {
        for (FileInfo info : docList) {
            if (info.getPath().equals(file.getPath())) {
                return;
            }
        }
        LogUtil.v("FileDocFragment", "addDocInfo file:" + file.getPath());
        FileInfo docInfo = new FileInfo();
        docInfo.setName(file.getName());
        docInfo.setSize(FileMg.getFileSizes(file));
        docInfo.setPath(file.getPath());
        docInfo.setFileType(file.getName().substring(
                file.getName().indexOf(".") + 1, file.getName().length()));
        docInfo.setTime(DateUtils.timeMillisToDateTimeString(file.lastModified(), DateUtils.FORMAT_5));
        docList.add(docInfo);
    }

    private class MyAsyncTask extends AsyncTask {
        @Override
        protected Object doInBackground(Object... arg0) {
            LogUtil.v("FileDocFragment", "MyAsyncTask doInback>>>>>>:");
            getMyLocalFile(new File(AppConstant.APP_DIR));
            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
